package cn.hiapi.core.basic.context;

import lombok.Getter;
import lombok.extern.slf4j.XSlf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author AdinZ
 * @date 2021/7/23 3:37 下午
 */
@Getter
@Component
public class DispatchContext implements ApplicationContextAware {

    private ApplicationContext context;


    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        this.context = context;
    }


    public <T> Map<String, T> getMap(@Nullable Class<T> clazz) {
        return this.context.getBeansOfType(clazz);
    }


    /**
     * 获取服务 ,多个时,只获取第一个
     *
     * @param clazz
     * @param <Service>
     * @return
     */
    public <Service> Service getServiceOne(Class<Service> clazz) {
        final Map<String, Service> serviceMap = this.context.getBeansOfType(clazz);
        if (serviceMap.isEmpty()) {
            System.out.println(DateFormatUtils.format(new Date(), "yyyy-MM-dd hh:mm:ss", Locale.CHINA) + "\t\t\t[获取service] 获取" + clazz.getCanonicalName() + "时为空 ");
            return null;
        }
        return serviceMap.values().stream().findFirst().get();
    }

    public <Service> Collection<Service> getServiceList(Class<Service> clazz) {
        final Map<String, Service> serviceMap = this.getMap(clazz);
        if (serviceMap == null || serviceMap.isEmpty()) return new ArrayList<>();
        return serviceMap.values();
    }


}
